package com.sinodata.bsm.center.engine.process;

import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.center.bean.ProcessRuleBean;
import com.sinodata.bsm.center.cache.SystemParameterCache;
import com.sinodata.bsm.center.util.AnalyzePropertiesUtil;
import com.sinodata.bsm.center.util.spring.SpringContextHolder;
import com.sinodata.bsm.common.constants.SystemParameterConstants;
import com.sinodata.bsm.common.vo.Event;
import com.sinodata.bsm.common.vo.ProcessRule;
import com.sinodata.bsm.common.vo.SystemParameter;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-4-15 下午4:29:58          liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class ProcessEngine {

    /**
     * 发送工单实现类的配置文件
     */
    private static final String filename = "WEB-INF/conf/send-process-impclass.properties";

    private static AnalyzePropertiesUtil prop = AnalyzePropertiesUtil.getInstance();

    private static Logger logger = Logger.getLogger(ProcessEngine.class);

    private static SystemParameterCache systemParameterCache = SpringContextHolder.getBean(SystemParameterCache.class);

    /**
     * 对一个事件发送工单
     * 
     * @param eventValue
     */
    public static void sendProcess(Event event) {
        Long resId = event.getResId();
        Long eventTypeId = event.getEventTypeId();
        Integer level = event.getLevel();
        SystemParameter parameter = systemParameterCache.get(SystemParameterConstants.PARAMETER_1);
        if (parameter != null && parameter.getValue().equals("0")) {//流程工单发送功能被暂停
            return;
        }
        //拿发送工单的规则
        List<ProcessRuleBean> rules = ProcessRuleBean.getAvailableProcessRules(resId, eventTypeId, level);
        for (ProcessRuleBean p : rules) {
            ProcessRule processRule = p.getProcessRule();
            String className = prop.getProperties(filename).get(processRule.getSendClass());
            //反射创建发送工单的实现类
            try {
                Object processSendImp = Class.forName(className).newInstance();
                ProcessSend processSend = (ProcessSend) processSendImp;
                //发送工单
                processSend.send(event);
            } catch (InstantiationException e) {

                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                logger.error("反射创建工单发送类[" + className + "]失败，请检查配置文件" + filename, e);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
